<template>
	<div class="knowledge-points">
		<el-row class="preview-head" type="flex" align="middle">
            <el-col :span="2" :offset="1">
                <el-button type="text" @click="goBack()"><i class="el-icon-arrow-left"></i>返回</el-button>
            </el-col>
            <el-col :span="1">
                <span>试卷范围:</span>
            </el-col>            
            <el-col :span="10">
                <testArea ref="testArea"></testArea>
            </el-col>
            <el-col :span="1" :offset="1">
                <span>试卷类型:</span>
            </el-col>  
            <el-col :span="6">
                <template >
                    <el-select v-model="manual.type " placeholder="请选择试题类型">
                        <el-option
                            v-for="(item, index) in getTestTypeList"
                            :key="index"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </template> 
            </el-col>            
            <el-col :span="2">
                <el-button type="primary"  @click="changeVisible" v-preventReClick>提交</el-button>
            </el-col>
		</el-row>

		<div class="knowledge-warp"  :class="setClass">
			
			<div class="knowledge-warp-l">
				<div class="nav-class-l">
					<span v-if="!classObject.isLeft"><i class="el-icon-arrow-left"></i>收起</span>
					<span v-else><i class="el-icon-arrow-right"></i>展开</span>
				</div>

				<input type="checkbox" name="type" v-model="classObject.isLeft">
				
				<knowledgeLeft ref="knowledgeLeft"></knowledgeLeft>

			</div>

			<div class="knowledge-warp-r">
				
				<div class="nav-class-r">
					<span v-if="!classObject.isRight"><i class="el-icon-arrow-right"></i>收起</span>
					<span v-else><i class="el-icon-arrow-left"></i>展开</span>
				</div>
				
				<input type="checkbox" name="type" v-model="classObject.isRight">
				<knowledgeRigth ref="knowledgeRigth" ></knowledgeRigth>

			</div>
		</div>

		<el-dialog
			title="提示"
			:visible.sync="dialogVisible"
			width="30%" customClass="dialog-box"
			:close-on-click-modal="false">
				<div class="authority">
					<div>
						<span>
							<input type="radio" name="radio" v-model="manual.authority" value="1">
							<i class="el-icon-circle-check"></i>
						</span>
						<p>公开</p>
					</div>
					<div>
						<span>
							<input type="radio" name="radio" v-model="manual.authority" value="0">
							<i class="el-icon-circle-close"></i>
						</span>
						<p>私有</p>
					</div>
				</div>
				<span slot="footer" class="dialog-footer">
					<el-button type="primary"  plain @click="dialogVisible = false">取 消</el-button>
					<el-button type="primary" @click="testChang">确 定</el-button>
				</span>
		</el-dialog>

	</div>
</template>


<script>
    import testArea  from  './test-area';

	// let manualObj = JSON.parse(sessionStorage.getItem('manualObj'));
	import bus  from  './../base/eventBus.js'
	import knowledgeLeft from './knowledge-points-l.vue';
	import knowledgeRigth from './knowledge-points-r.vue'
	export default {
		components: { 
            knowledgeLeft,
            knowledgeRigth,
            testArea
        },
		data(){
			return{
				headClassList: null,
				chapterID: '',	/*章节id*/
				knowledgeID: '', /*知识点id*/
				manual: {
					grade: '', 		/*年级id*/
					subject: '',    /*科目id*/
					edition: '', 	/*版本id*/
					material: '',	/*教材*/
					authority: 0,
					type:''
				},
				gradeLsit: [], 		/*年级列表*/
				subjectLsit: [], 	/*科目列表*/
				editionList: [], 	/*版本列表*/
				materialList: [],	/*教材*/
				questionArray: [],
				getTestTypeList: [],
				dialogVisible: false,
				
				classObject: {	/*左右收起 & 展开*/
					isLeft: false,
					isRight: false,
				},
				testName: ''

			}
		},
		computed: {
			setClass(){
				 if(this.classObject.isLeft == true && this.classObject.isRight == true){
					return 'knowledge-sidebarQ'
				}else if (this.classObject.isLeft == true && this.classObject.isRight == false) {
					return 'knowledge-sidebarL'
				}else if(this.classObject.isRight == true && this.classObject.isLeft == false){
					return 'knowledge-sidebarR'
				}
			}
		},
		created(){
			bus.$on("setQuestion", (questionTyle) => {
				this.questionArray = questionTyle
			});
		},
		mounted(){
			this.headClassList = document.querySelector('#trunk').classList;
			this.headClassList.add('hidden-knowledge')


			this.$nextTick(()=>{

				let manual = new Promise((resolve, reject) => {
				    //做一些异步操作
				    setTimeout(() => {
				      let manualObj =  JSON.parse(sessionStorage.getItem('manualObj'));
				        resolve(manualObj);
				    },800);
				});
				manual.then((result) => {
                    this.$refs.testArea.edit = {
                        grade: result.grade,	/*年级id*/
                        subject: result.subject,    /*科目id*/
                        edition: result.edition, /*	版本id*/
                        material: result.course_id,	/*教材*/
                    };
                    this.$refs.testArea.getGrade();
				   	this.manual.type =  result.type;	/*类型*/
				   	this.getTestType()
				})


			
			})

		},
		destroyed(){
			this.headClassList.remove('hidden-knowledge')
			sessionStorage.removeItem('manualObj')
		},
		methods: {
			/*
				根据需求判断试卷的修改保存数据
			 */
			replaceTest(type){

				if (this.$route.query.copy) {
					/*type 1保存， 0删除*/
					let success = ()=>{

					}
					let data  = {}
					if (type == 1) {
						data = {
							old_id: this.$route.query.copy,
							new_id: this.$route.query.edit
						}
						this.$ajax.put('api/newtest/replace_test', data, {func: {success: success}})
					}else{

						this.$ajax({
							url: 'api/newtest/replace_test',
							method: 'delete',
							params: {new_id: this.$route.query.edit},
							func: { success: success}
						})
					}
				}

			},
			/*题目范围:*/
			topicScope(){

				let success = (res =>{
					// this.$message.success(res.msg)
				});

				let testID = ''
				if (this.$route.query.id) {
					testID = this.$route.query.id
				}else{
					testID = this.$route.query.edit
				}

				let params = {
					id: testID,/*试卷名*/
					create_id: 		this.$g.user_id,
                    grade_id: this.$refs.testArea.ruleForm.grade,
                    subject_id: this.$refs.testArea.ruleForm.subject,
                    version_id: this.$refs.testArea.ruleForm.edition,
                    course_id: this.$refs.testArea.ruleForm.material,                    
                    source_id: 		this.manual.type,
					authority: 0,
					status: 1,
				};

				this.$ajax.put('api/newtest/save_test', params, {func: {success: success}})
			},
			/*
				提交试卷数据
			*/
			changeVisible(){
                
                // 先验证试卷范围里的几个select框的值是否选择
                this.$refs.testArea.valid();
             
                let noSelect = Object.values(this.$refs.testArea.ruleForm).includes('');
                if(noSelect)return;			

                if (this.questionArray.length === 0) {return this.$message.error("请组卷再提交")};
                
				if (this.$store.state.testName == null) {
					this.$refs.knowledgeRigth.setTestName()
                }
                console.log('5')
				this.topicScope()
				this.testChang()
			
			},
			/**
			 * 试卷的试题排序
			 * @DateTime 2019-08-13T15:27:53+0800
			 * @return   {[type]}                 [description]
			 */
			testChang(){

				let [idex, questionList] = [1, []]
				this.questionArray.forEach((item, index) =>{
					item.children.forEach((child, list) =>{
						questionList.push({
							'question_id': child.id,
							'score': child.score,
							'sort': idex++
						})
					})
				});


				let success = (res=>{
					// this.$message.success(res.msg)
					this.submitTest()
				});

				let testID = ''

				if (this.$route.query.id) {
					testID = this.$route.query.id
				}else{
					testID = this.$route.query.copy
				}

				let params = {test_id: testID, question_list: questionList};
				this.$ajax.put('api/newtest/change_test', params, {func: {success: success}})
			},
			/**
			 * 提交新建的试卷
			 * @DateTime 2019-08-12T14:29:15+0800
			 * @return   {[type]}                 [description]
			 */
			submitTest(){
				let status = '';
				if (this.manual.authority == 1) {
					status = 3
				}else if (this.manual.authority ==  0){
					status = 1
				}

				let testID = ''
				if (this.$route.query.id) {
					testID = this.$route.query.id
				}else{
					testID = this.$route.query.copy
				}

				let success = (res =>{
					// this.$message.success(res.msg)
					this.$store.commit('SET_TESTNAME', null)
					this.dialogVisible = false
					this.replaceTest(1)
					if (this.$route.query.points == 1) {
						this.$router.push({path: '/test/test-paper', query: {id: testID, authority: 2}})
					}else{
						this.$router.push({path: '/test/preview-test', query: {id: testID, 'points': 2}})
					}

					
				});

				let params = {
					name: this.$store.state.testName,
					id: testID,/*试卷名*/
					status: status,/*状态 1正常 0删除 2未通过 3未处理*/
					authority: this.manual.authority,/*是否公开 1 公开 2不公开*/
					// difficulty_id: ,/*难度id*/
				};

				this.$ajax.put('api/newtest/save_test', params, {func: {success: success}})
			},
			/**
			 * 请求试题类型数据
			 * @DateTime 2019-07-25T14:09:13+0800
			 * @return   {[type]}                 [description]
			 */
			getTestType(){

				let success = (res=>{
					this.getTestTypeList = res.data;

					if (this.getTestTypeList.length > 0) {
						this.getTestTypeList.unshift({id:0, name: '无试卷类型'})
					}
				});

				let params = {status: 1};

				this.$ajax({
					url: 'api/newtest/get_test_type',
					method: 'get',
					params: params,
					func: { success: success}
				})
			},

			/**/
			delTest(){

				let len = this.$refs.knowledgeLeft.changQuestionid()
				let success = (res=>{
					this.$router.back(-1)
				});
				this.$ajax({
					url: 'api/test/bind_one_question_to_test',
					method: 'delete',
					params: {
						testid: this.$route.query.edit,
						question_id: len
					},
					func: { success: success}
				})
			},
			goBack(){
				// console.log(this.$refs.knowledgeLeft.changQuestionid())
				this.$confirm('返回将不保存当前创建的试卷内容，是否继续？', '提示', {
					cancelButtonText: '取消',
					confirmButtonText: '确定',
					type: 'warning',
					customClass: "test-message"
				}).then(() => {
					/*新建返回删除*/
					if (this.$route.query.id) {
						let success = (res=>{
							this.$router.back(-1)
							
						});
						this.$ajax({
							url: 'api/test/test_del_one',
							method: 'delete',
							params: {id: this.$route.query.id},
							func: { success: success}
						})
					}else{
						this.replaceTest(0)
						// this.delTest()
						/*编辑返回*/
						this.$router.push('/test/private-library')
					}

				
				}).catch(() => {});
			},
			
		}
	}
</script>